<template>
    <div class="banner-list-wrap">
        <el-space class="button-group">
            <el-button type="primary" @click="refreshHandler">刷新</el-button>
            <el-button type="primary" @click="dialogVisible=true">上传</el-button>
        </el-space>

        <!-- 轮播列表展示和轮播新增 -->
        <el-table border :data="bannerList">
            <el-table-column label="轮播id" prop="bannerid" align="center"></el-table-column>
            <el-table-column label="轮播图片" align="center">
                <template v-slot="{ row }">
                    <el-image style="width:200px" :src="row.img"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="轮播链接" prop="link" align="center"></el-table-column>
            <el-table-column label="轮播提示" prop="alt" align="center"></el-table-column>
            <el-table-column label="轮播展示" align="center" v-if="judegPermission(['super'])">
                <template v-slot="{ row }">
                    <el-switch v-model="row.flag" :disabled="!judegPermission(['super'])" @change="changeHandler($event, row.bannerid)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" v-permission:remove = "['super']">
                <template v-slot="{ row }">
                    <el-button @click="deleteHandler(row.bannerid)"   v-permission:disabled = "['super']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <el-dialog v-model="dialogVisible" title="图片上传" width="50%" :before-close="handleClose">
        <el-form ref="uploadForm" :model="uploadParams" label-width="80px" :rules="rules">
            <el-form-item label="选择图片" prop="img">
                <el-upload 
                    ref="uploadFile"
                    v-model:file-list="fileList"
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                    :auto-upload="false" 
                    :limit="1"
                    list-type="picture-card"
                    :on-preview="previewHandler"
                    :on-remove="removeHandler"
                    :on-exceed="exceedHandler"
                    :on-change="uploadChangeHandler"
                >
                    <!-- 默认插槽  点击图片上传 -->
                    <el-icon size="100"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="跳转地址" prop="link">
                <el-input v-model="uploadParams.link"></el-input>
            </el-form-item>
            <el-form-item label="图片提示" prop="alt">
                <el-input v-model="uploadParams.alt"></el-input>
            </el-form-item>
            <el-form-item >
                <el-button @click="submitHandler">提交</el-button>
                <el-button type="primary"  @click="resetHandler">取消</el-button>
            </el-form-item>
        </el-form>
        
        <!-- <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="dialogVisible = false">
                    Confirm
                </el-button>
            </div>
        </template> -->
    </el-dialog>
</template>

<script>
import { getBannerListAPI, delBannerListAPI, updateBannerFlagAPI,addBannerAPI } from "@/api/banner";
import _ from "lodash";

import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'

import mixinPermission from "@/mixins/permission";

import { mapMutations } from "vuex";


export default {
    name: "BannerListView",
    mixins:[mixinPermission],
    data() {
        return {
            bannerList: null,
            dialogVisible:false,
            uploadParams:{
                img:"",
                link:"",
                alt:"",
            },
            rules:{
                img:[{type:"string",required:true,message:"请传入图片地址",trigger:"blur"}],
                link:[{type:"string",required:true,message:"请传入图片跳转地址",trigger:"blur"}],
                alt:[{type:"string",required:true,message:"请传入图片提示信息",trigger:"blur"}],
            },
            // 本地上传相关
            fileList:[],
        }
    },
   
    methods: {
        ...mapMutations(["startLoading","endLoading"]),
        async getBannerList() {
            try {
                let result = await getBannerListAPI();
                console.log("请求成功", result);
                this.bannerList = result.data;
            } catch (err) {
                ElMessage({
                    type: "error",
                    message: err.message,
                })
            }
        },
        async changeHandler(flag, bannerid) {
            try {
                let result = await updateBannerFlagAPI({ bannerid, flag });
                console.log("修改成功", result);
            } catch (err) {
                ElMessage({
                    type: "error",
                    message: err.message,
                })
            }
        },
        async deleteHandler(bannerid) {
            console.log(1111,bannerid);
            try {
                let result = await delBannerListAPI({bannerid:bannerid});  // 删除数据
                console.log("删除成功", result);

                // this.getBannerList();  // 重新请求更新视图 (发送ajax请求 => 慢)
                var index = this.bannerList.findIndex(v=>v.bannerid == bannerid);  // 修改数据 => 快
                this.bannerList.splice(index,1);

            } catch (err) {
                ElMessage({
                    type: "error",
                    message: err.message,
                })
            }
        },
        refreshHandler: _.debounce(function () {
            this.getBannerList();
        }, 300),
        async addBanner(){
            let result = await addBannerAPI(this.uploadParams);
            console.log("上传成功", result);
        },
        async submitHandler(){
            this.$refs.uploadForm.validate().then(async ()=>{
                console.log("校验成功");
                await this.addBanner();  // 等上传成功之后
                this.resetHandler()   // 清空表单
                this.$refs.uploadFile.clearFiles(); // 先清除上传列表
                this.dialogVisible = false;  // 隐藏遮罩层

                this.getBannerList();  // 上传成功,更新页面
            }).catch(err=>{

            });
        },
        resetHandler(){
            this.$refs.uploadForm.resetFields();
        },

        // 本地上传
        previewHandler(file){
            console.log("点击预览图片",file);
        },
        removeHandler(file){
            console.log("点击删除图片",file);
        },
        exceedHandler(fileList){ // 超出的文件列表 (超出的可能不止一个 => 数组)
            console.log("超出限制",fileList);

            this.$refs.uploadFile.clearFiles(); // 先清除上传列表
            let file = fileList[0]; // 取超出的文件列表中的第一个
            this.$refs.uploadFile.handleStart(file); //手动选择文件
        },
        uploadChangeHandler(file){  
            console.log("图片切换",file);   // 把File文件(vue处理版本)转化为Base64格式的字符串(当前后端不能接受File对象)
            // file.raw  => 原生文件对象

            var reader = new FileReader();  // 文件读取对象
            reader.readAsDataURL(file.raw);   // File文件转化为Base64
            reader.onload = () => { 
                console.log(reader.result); // base64
                this.uploadParams.img = reader.result; 
            } 
                    
        }
        

    },
    async mounted() {
        await this.getBannerList();
        this.endLoading();
        this.$np.done();

        // 模拟网络延迟高的问题
        // setTimeout(()=>{
        //     this.endLoading();
        //     this.$np.done();
        // },5000);
    },
    beforeRouteEnter(to,from,next){
        next((vm)=>{
            vm.startLoading();
            vm.$np.start();
            vm.$np.inc();
        });
    }   
}
</script>

<style lang="scss" scoped>
.banner-list-wrap {
    padding: 20px;
}

.button-group {
    margin-bottom: 20px;
}
</style>